// store/permission.ts
import type { MenuOption } from 'naive-ui'
import { defineStore } from 'pinia'
import { RouteRecordRaw } from 'vue-router'

import { getPermission } from '@/apis/index'
import { catchToTuple, convertToMenuComponentData, convertToRoutes } from '@/utils'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    permissions: [] as string[],
    routes: [] as RouteRecordRaw[],
    menus: [] as any[],
  }),
  actions: {
    async init() {
      try {
        const [err, response] = await catchToTuple(getPermission())

        if (err) {
          localStorage.removeItem('token')
          localStorage.removeItem('tab')
          return
        }

        const { code, data } = response

        if (code === 200 && data?.routes) {
          this.setPermissions(data.permissions || [])
          this.routes = convertToRoutes(data.routes)
          this.menus = convertToMenuComponentData(data.routes)

          console.log(this.routes)
        }
      } catch (error) {
        console.error('Failed to initialize permission store:', error)
        localStorage.removeItem('token')
        localStorage.removeItem('tab')
      }
    },
    hasPermission(permission: string): boolean {
      return this.permissions.includes(permission)
    },
    setPermissions(permissions: string[]) {
      this.permissions = permissions
    },
  },
  getters: {
    getRoutes(state): RouteRecordRaw[] {
      return state.routes
    },
    getMenus(state): MenuOption[] {
      return state.menus
    },
    getPermissions(state): string[] {
      return state.permissions
    },
  },
})
